var WxParse = require('../../wxParse/wxParse.js');
var app = getApp();
const bgMusicAudioContext = wx.getBackgroundAudioManager();
var timer;
Page({
  data: {
    curSlideIndex: 0,
    isShowbargainprice:false,//是否显示砍价提示弹出层
    isShowshare: false,//是否显示分享弹出层
    isShowbuyModal: false,//购买弹出层
    videoShow: false
  },
  onLoad: function (e) {
    var that = this;
    if (e && e.enterfrom) {
      var enterfrom = e.enterfrom == 'share' ? true : false;
      that.setData({
        enterfrom: enterfrom
      })
    }
    app.setNavColor(that);
    app.setNavtitle('商品详情');
    if (e) {
      if (e.scene) {
        var scene = decodeURIComponent(e.scene).split('&');
        console.log(scene);
        var secneObj = {};
        for (var i = 0; i < scene.length; i++) {
          var arr = scene[i].split('=');
          var key = arr[0];
          secneObj[key] = arr[1];
        }
        e = secneObj;
      }
      if (e.id) {
        var activeId = e.id;
        that.setData({
          activeId: activeId
        })
      }
      if (e.jid) {
        var jid = e.jid;
        that.setData({
          jid: jid,
          shareEnter:true
        })
      }
      if(e.mid){
        that.setData({
          mid:e.mid
        })
      }
    }
    if (!app.globalData.plumSession) {
      app.plumSessionCallback = plumSession => {
        
          console.log('查询到登录信息');
          that.requestDetail();
          that.setData({
            isHasunionid: app.globalData.isHasunionid,
            haveVcmCard: app.globalData.haveVcmCard
          })
        
      }
    }else{
      that.getSlient();
      var mid = that.data.mid ? that.data.mid : '';
      that.setData({
        myMid:app.globalData.userInfo.mid
      })
      app.globalData.requestUrl = app.getNewRequestUrl(mid);
      that.requestDetail();
      that.setData({
        isHasunionid: app.globalData.isHasunionid,
        haveVcmCard: app.globalData.haveVcmCard
      })
    }
  },
  onReady: function () {
    var that = this;
    that.videoContext = wx.createVideoContext('myVideo');

  },
  onHide: function () {
    this.hideVideo();
  },
  onUnload:function(){
    clearTimeout(timer);
  },
  onShow: function () {
    var that = this;
    that.setData({
      slient: app.globalData.slient ? app.globalData.slient:''
    });
    if (app.globalData.slient == 1) {
      that.setData({
        isShowgetuser: true
      })
    }
  },
  initPage: function(){
    var that = this;
    that.onLoad();
    that.onShow();
  },
  getSlient:function(){
    var that = this;
    var slient = app.globalData.slient ? app.globalData.slient:'';
    that.setData({
      slient: slient
    })
    // if (slient == 1) {
    //   wx.hideTabBar()
    // }
  },
  hideGetuser: function () {
    var that = this;
    that.setData({
      isShowgetuser: false
    })
  },
  // 获取用户信息
  getuserInfo: function (e) {
    var that = this;
    if (e.detail.userInfo) {
      var userdata = e.detail;
      console.log(userdata);
      var slient = that.data.slient;
      var again = false;
      if (slient == 0) {
        again = true;
      }
      app.getuserInfo(that, userdata, again);
    }
  },
  //播放视频
  playVideo: function () {
    var that = this;
    if (app.globalData.isPlay) {
      bgMusicAudioContext.stop();
      app.globalData.curInfoMusicid = '';
      app.globalData.isPlay = false;
      app.globalData.isPlaynew = 'new';
    } 
    that.setData({
      isShowVideo: true
    })
    that.videoContext.play();
  },
  // 关闭视频
  hideVideo: function () {
    var that = this;
    that.setData({
      isShowVideo: false
    })
  },
  peiviewImg: function (e) {
    var curimg = e.currentTarget.dataset.curimg;
    var imgs = e.currentTarget.dataset.imgs;
    wx.previewImage({
      current: curimg, // 当前显示图片的http链接
      urls: imgs // 需要预览的图片http链接列表
    })
  },
  requestDetail: function () {
    var that = this;
    //发起请求，获取列表列表
    var id = that.data.activeId;
    var data = {
      map: 'applet_bargain_activity_detail',
      aid: id
    };
    if (that.data.jid){
      data.jid = that.data.jid;
    }
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      success: function (res) {
        if (res.data.ec == 200) {
          console.log(res.data.data);
          var activity = res.data.data.activity;
          if (activity.video != '') {
            that.setData({
              video: activity.video,
              videoShow: true,
            })
          }
          /** 规格库存判断开始 **/
          if (activity.formatList && activity.formatList.length == 1) {
            for (let i in activity.formatList[0].value) {
              if (activity.formatValueNew[activity.formatList[0].value[i].name].stock == 0) {
                activity.formatList[0].value[i].noCheck = true;
              }
            }
          }
          /** 规格库存判断结束 **/
          that.setData({
            activity: activity,
            detailInfo: res.data.data,
            hasFormat: activity.hasFormat,
          })
          that.countDownTime();
          var article1 = that.data.activity.rule;
          // 富文本解析
          WxParse.wxParse('article1', 'html', article1, that, 5);
          var article = that.data.activity.detail;
          // 富文本解析
          WxParse.wxParse('article', 'html', article, that, 5);
        } else {
          app.errorTip(that, res.data.em, 2000);
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  dotsChange: function (e) {//改变当前幻灯索引
    this.setData({
      curSlideIndex: e.detail.current
    })
  },
  // 我要参加
  participateIn:function(){
    var that = this;
    if (app.globalData.slient == 1 || (this.data.isHasunionid == 0 && this.data.haveVcmCard == 1)) {
      return;
    }
    //发起请求，获取列表列表
    var id = that.data.activeId;
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: {
        map: 'applet_bargain_activity_join',
        aid: id
      },
      success: function (res) {
        if (res.data.ec == 200) {
          console.log(res.data.data);
          app.errorTip(that, res.data.data.msg, 2000);
          that.setData({
            shareEnter: false,
            jid: res.data.data.jid
          })
          that.requestDetail();
        } else {
          if(res.data.jid){
            that.setData({
              shareEnter: false,
              jid: res.data.jid
            })
            that.requestDetail();
          }else{
            app.errorTip(that, res.data.em, 2000);
          }
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  // 立即砍价
  nowBargain: function () {
    var that = this;
    if (app.globalData.slient == 1 || (this.data.isHasunionid == 0 && this.data.haveVcmCard == 1)) {
      return;
    }
    //发起请求，获取列表列表
    var id = that.data.activeId;
    var mid = that.data.detailInfo.record.mid;
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: {
        map: 'applet_bargain_activity_help',
        aid: id,
        mid: mid
      },
      success: function (res) {
        if (res.data.ec == 200) {
          console.log(res.data.data);
          var bargainInfo = res.data.data;
          that.setData({
            bargainInfo: bargainInfo,
            isShowbargainprice:true,
            bargainSuccess:true
          })
          that.requestDetail();
        } else {
          app.errorTip(that, res.data.em, 2000);
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  toBargainrecord:function(){//砍价记录
    var that = this;
    var id = that.data.activeId;
    var jid = that.data.detailInfo.record&&that.data.detailInfo.record.bjId ? that.data.detailInfo.record.bjId:'';
    wx.navigateTo({
      url: '/subpages0/bargainRecords/bargainRecords?id=' + id + '&jid=' + jid
    })
  },
  seeOrder:function(){//查看订单
    var that = this;
    var id = that.data.detailInfo.tid;
    wx.navigateTo({
      url: '/subpages/bargainOrderDetail/bargainOrderDetail?id=' + id
    })
  },
  toBargainOrder:function(){
    var that = this;
    var baId = that.data.activity.id;
    var isFormat = that.data.hasFormat;
    var orderArr = [];
    var orderObj = {};
    orderObj.gid = that.data.activity.gid;
    orderObj.num = 1;
    if (that.data.chooseGuige) {
      var gfid = that.data.chooseGuige.id;
      orderObj.gfid = gfid;
      var formatStock = parseInt(that.data.chooseGuige.stock);
    }
    
    var stock = formatStock ? formatStock : that.data.activity.stock;
    console.log(stock)
    orderArr.push(orderObj);
    var data = {};
    data.map = 'applet_order_create';
    data.buys = encodeURI(JSON.stringify(orderArr));
    data.baId = baId;
    console.log(app.globalData.requestUrl);
    if (isFormat && !gfid) {
      app.errorTip(that, '请选择商品规格！', 2000);
      return;
    }
    if (!orderObj.num || orderObj.num <= 0) {
      app.errorTip(that, '请输入正确的商品数量', 2000);
      return;
    }
    console.log("库存数量" + stock);
    console.log("商品数量" + orderObj.num);
    if (orderObj.num > stock) {
      app.errorTip(that, '商品数量超出库存', 2000);
      return;
    }
    //发起请求，获取列表列表
    wx.showLoading({
      title: '加载中'
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      success: function (res) {
        if (res.data.ec == 200) {
          console.log(res.data.data);
          wx.setStorage({
            key: "submitOrder",
            data: res.data.data,
            success: function (res) {
              console.log(res);
              // wx.navigateTo({
              //   url: '/subpages/bargainOrderForm/bargainOrderForm'
              // })
              wx.navigateTo({
                url: '/pages/waitBuyerPay/waitBuyerPay'
              })
            }
          })
        } else {
          app.errorTip(that, res.data.em, 2000);
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  showBargainmodal:function(){
    this.setData({
      isShowbargainprice: true
    })
  },
  hideBargainmodal:function(){
    this.setData({
      isShowbargainprice: false
    })
  },
  showSharemodal(){
    var id = this.data.activeId;
    var jid = this.data.detailInfo.record && this.data.detailInfo.record.bjId ? this.data.detailInfo.record.bjId : '';

    var pageShare = this.selectComponent('.page-share'), 
    posterData={map:'applet_bargain_share_info',activityId: id,jid: jid};
    console.log(posterData)
    this.setData({
      posterData:posterData
    })
    pageShare.showSharemodal()
  },
  hideSharemodal(){
    var pageShare = this.selectComponent('.page-share');
    pageShare.hideSharemodal()
  },
  

  chooseGuige: function (e) {
    var that = this;
    var findex = e.currentTarget.dataset.findex;
    var index = e.currentTarget.dataset.index;
    var disabled = e.currentTarget.dataset.disabled;
    if (disabled) return;
    var activity = that.data.activity;
    var checkFormat = [];
    for (var i = 0; i < activity.formatList[findex].value.length; i++) {
      if (index == i) {
        activity.formatList[findex].value[index].checked = !activity.formatList[findex].value[index].checked;
        if (findex == 0 && activity.formatList[findex].value[index].checked) {
          var curImgformat = activity.formatList[0].value[index];
          that.setData({
            curImgformat: curImgformat
          })
        } else {
          if (findex == 0) {
            that.setData({
              curImgformat: ''
            })
          }
        }
      } else {
        activity.formatList[findex].value[i].checked = false;
      }
    }
    for (var i = 0; i < activity.formatList.length; i++) {
      for (var j = 0; j < activity.formatList[i].value.length; j++) {
        if (activity.formatList[i].value[j].checked) {
          checkFormat.push(activity.formatList[i].value[j]);
        }
      }
    }
    /** 规格库存判断开始 **/
    for (let k in activity.formatList) {
      for (let n in activity.formatList[k].value) {
        activity.formatList[k].value[n].noCheck = false
      }
    }

    for (let i in activity.formatValueNew) {
      let noStockArr = [];
      let formatValueItem = i.split('-');
      switch (checkFormat.length) {
        case 1:
          if (formatValueItem.indexOf(checkFormat[0].name) != -1 && activity.formatValueNew[i]['stock'] == 0 && activity.formatList.length == 2) {
            formatValueItem[formatValueItem.indexOf(checkFormat[0].name)] = '';
            noStockArr = formatValueItem;
          } else if (activity.formatValueNew[i]['stock'] == 0 && activity.formatList.length == 1) {
            noStockArr.push(i);
          } else if (formatValueItem.indexOf(checkFormat[0].name) != -1 && activity.formatValueNew[i]['stock'] == 0 && activity.formatList.length == 3) {
            noStockArr = [];
          }
          break;
        case 2:
          if ((formatValueItem.indexOf(checkFormat[0].name) != -1 && formatValueItem.indexOf(checkFormat[1].name) != -1) && activity.formatValueNew[i]['stock'] == 0 && activity.formatList.length == 3) {
            formatValueItem[formatValueItem.indexOf(checkFormat[0].name)] = '';
            formatValueItem[formatValueItem.indexOf(checkFormat[1].name)] = '';
            noStockArr = formatValueItem;
          } else if ((formatValueItem.indexOf(checkFormat[0].name) != -1 || formatValueItem.indexOf(checkFormat[1].name) != -1) && activity.formatValueNew[i]['stock'] == 0 && activity.formatList.length == 2) {
            if (formatValueItem.indexOf(checkFormat[0].name) != -1) {
              formatValueItem[formatValueItem.indexOf(checkFormat[0].name)] = '';
            }
            if (formatValueItem.indexOf(checkFormat[1].name) != -1) {
              formatValueItem[formatValueItem.indexOf(checkFormat[1].name)] = '';
            }
            noStockArr = formatValueItem;
          }
          // console.log(noStockArr);
          break;
        case 3:
          if (activity.formatValueNew[i]['stock'] == 0 && (formatValueItem.indexOf(checkFormat[0].name) != -1 || formatValueItem.indexOf(checkFormat[1].name) != -1 || formatValueItem.indexOf(checkFormat[2].name) != -1)) {
            for (let q in checkFormat) {
              formatValueItem[formatValueItem.indexOf(checkFormat[q].name)] = '';
            }
            if (formatValueItem[0] === '') {
              formatValueItem[1] = formatValueItem[2] = formatValueItem[1] + formatValueItem[2]
            }
            if (formatValueItem[1] === '') {
              formatValueItem[0] = formatValueItem[2] = formatValueItem[0] + formatValueItem[2]
            }
            if (formatValueItem[2] === '') {
              formatValueItem[0] = formatValueItem[1] = formatValueItem[0] + formatValueItem[1]
            }
            console.log(formatValueItem);
            noStockArr = formatValueItem
          }
          break;
      }
      console.log(noStockArr);
      for (let k in activity.formatList) {
        for (let n in activity.formatList[k].value) {
          if (noStockArr.indexOf(activity.formatList[k].value[n].name) != -1) {
            activity.formatList[k].value[n].noCheck = true
          }
        }
      }
    }
    // 单规格库存判断
    if (activity.formatList.length == 1) {
      for (let i in activity.formatList[0].value) {
        if (activity.formatValueNew[activity.formatList[0].value[i].name].stock == 0) {
          activity.formatList[0].value[i].noCheck = true;
        }
      }
    }
    /** 规格库存判断结束 **/
    console.log(activity.formatList);
    that.setData({
      activity: activity,
      checkFormat: checkFormat
    })
    if (checkFormat.length == activity.formatList.length) {
      var formatName = '';
      for (var i = 0; i < checkFormat.length; i++) {
        formatName += checkFormat[i].name;
        if (i < checkFormat.length - 1) {
          formatName += '-';
        }
      }
      console.log(formatName);
      console.log(activity.formatValueNew);
      var chooseGuige = activity.formatValueNew[formatName];
      chooseGuige.formatName = formatName;
      chooseGuige.formatName = formatName;
      console.log(chooseGuige);
      that.setData({
        chooseGuige: chooseGuige
      })
    } else {
      that.setData({
        chooseGuige: {
          stock: activity.stock
        }
      })
    }
  },
  nowbuy: function () {
    var that = this;
    if (app.globalData.slient == 1 || (this.data.isHasunionid == 0 && this.data.haveVcmCard == 1)) {
      return;
    }
    if (that.data.activity.status == 2){
      return;
    }
    if (!app.globalData.plumSession) {
      wx.showModal({
        title: '操作提示',
        content: '允许授权后才可进行其它操作哦',
        showCancel: false,
        confirmText: '确定',
        confirmColor: '#1AAD16',
        success: function (res) {
          if (res.confirm) {
            wx.reLaunch({
              url: '/pages/singlePage/singlePage'
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      console.log("暂未获取到信息");
    } else {
      that.setData({
        isShowbuyModal: true,
        modalOperaType: "buy"
      })
    }
  },
  hidebuyModal: function () {
    var that = this;
    that.setData({
      isShowbuyModal: false
    })
  },
  // 活动剩余时间
  countDownTime: function () {
    // console.log("活动剩余时间")
    var that = this;
    var endTime = that.data.activity.endTime;
    var startTime = that.data.activity.startTime;
    endTime = endTime * 1000;
    startTime = startTime * 1000;
    var curTime = (new Date()).getTime();
    // console.log("当前时间" + leftTime);
    var leftTime;
    if (startTime - curTime > 0) {
      leftTime = startTime - curTime;
      that.setData({
        start: '开始'
      })
    } else {
      leftTime = endTime - curTime;
      that.setData({
        start: '结束'
      })
    }
    that.countDown(leftTime);
    timer = setTimeout(function () {
      that.countDownTime();
    }, 1000)
  },
  countDown: function (leftTime) {
    var that = this;
    var leftTime = leftTime;
    if (leftTime > 0) {
      var days = parseInt(leftTime / 1000 / 60 / 60 / 24, 10); 
      var hours = parseInt(leftTime / 1000 / 60 / 60 % 24, 10);
      var minutes = parseInt(leftTime / 1000 / 60 % 60, 10);
      var seconds = parseInt(leftTime / 1000 % 60, 10);
      days = days < 10 ? '0' + days : days;
      hours = hours < 10 ? '0' + hours : hours;
      minutes = minutes < 10 ? '0' + minutes : minutes;
      seconds = seconds < 10 ? '0' + seconds : seconds;
      var remainTime = {
        days: days,
        hours: hours,
        minutes: minutes,
        seconds: seconds
      }
      that.setData({
        remainTime: remainTime
      })
      if (days == '00' && hours == '00' && minutes == '00' && seconds == '00') {
        clearTimeout(timer);
      }
    } else {
      var remainTime = {
        days: '00',
        hours: '00',
        minutes: '00',
        seconds: '00'
      }
      that.setData({
        remainTime: remainTime
      })
      clearTimeout(timer);
    }
  },
  // VR视图
  toWebview: function (e) {
    var that = this;
    var vrurl = e.currentTarget.dataset.vrurl;
    var cover = e.currentTarget.dataset.cover;
    var title = e.currentTarget.dataset.title;
    var vrInfo = {
      vrurl: vrurl,
      cover: cover ? cover : '',
      title: title ? title : ''
    }
    wx.setStorage({
      key: 'webviewUrl',
      data: vrInfo,
      success: function () {
        wx.navigateTo({
          url: '/pages/commonView/commonView',
        })
      }
    })
  },
  backsy:function(){
    app.backHome();
  },
  //单张图片预览
  singlePeiviewImg: function (e) {
    var curimg = e.currentTarget.dataset.curimg;
    var imgs = new Array(e.currentTarget.dataset.imgs);
    wx.previewImage({
      current: curimg, // 当前显示图片的http链接
      urls: imgs // 需要预览的图片http链接列表
    })
  },
  onShareAppMessage: function (e) {
    var that = this;
    // var title = that.data.activity.name;
    var mid = app.globalData.userInfo.mid;
    var title = that.data.activity.desc ? that.data.activity.desc : that.data.activity.name;
    var cover = that.data.activity.shareImg ? that.data.activity.shareImg : that.data.activity.slide[0];
    var id = that.data.activeId;
    var jid = that.data.detailInfo.record && that.data.detailInfo.record.bjId ? that.data.detailInfo.record.bjId : '';
    var shareType = e.from;
    var pathUrl = '/subpages/bargainGoodDetail/bargainGoodDetail?enterfrom=share&id=' + id + '&mid=' + mid;
    if (shareType == 'button'){
      pathUrl = pathUrl + '&jid=' + jid;
    }
    app.getPoint(that);
    return {
      title: title,
      imageUrl: cover,
      path: pathUrl
    }
  },
})